// pages/bank-card/bank-card.ts
import { BankCardAPI } from '../../utils/profile-api';

interface BankCard {
  cardId: number;
  bankName: string;
  bankCode?: string;
  branchName?: string;
  cardNumberMasked: string;  // 银行卡号后四位
  cardHolderName: string;
  cardType: number;          // 1-借记卡，2-贷记卡，3-对公账户
  cardTypeName?: string;
  isDefault: number;         // 0-否，1-是
  isVerified?: number;
  status?: number;
  statusName?: string;
}

interface BankCardDetail {
  cardId: number;
  bankName: string;
  bankCode?: string;
  branchName?: string;
  cardNumber?: string;           // 完整卡号
  cardNumberMasked?: string;      // 脱敏卡号
  cardHolderName: string;
  cardHolderIdcardMasked?: string; // 脱敏身份证号
  cardHolderPhoneMasked?: string;  // 脱敏手机号
  cardType: number;
  cardTypeName?: string;
  isDefault: number;
  isVerified?: number;
  verifiedAt?: string;
  status?: number;
  statusName?: string;
  lastUsedAt?: string;
  createdAt?: string;
}

Page({
  data: {
    statusBarHeight: 0,
    bankCards: [] as BankCard[],
    loading: false,
    showDetailModal: false,
    cardDetail: null as BankCardDetail | null,
    loadingDetail: false
  },

  onLoad() {
    // 使用新的API替代已废弃的 wx.getSystemInfoSync
    try {
      const windowInfo = wx.getWindowInfo();
      this.setData({
        statusBarHeight: windowInfo.statusBarHeight || 0
      });
    } catch (error) {
      // 兼容旧版本，如果新API不可用则使用旧API
      const systemInfo = wx.getSystemInfoSync();
      this.setData({
        statusBarHeight: systemInfo.statusBarHeight || 0
      });
    }
    
    // 加载银行卡列表
    this.loadBankCardList();
  },

  onShow() {
    // 每次显示页面时刷新列表（可能从添加页面返回）
    this.loadBankCardList();
  },

  /**
   * 加载银行卡列表
   */
  async loadBankCardList() {
    this.setData({ loading: true });
    
    try {
      const res = await BankCardAPI.getBankCardList();
      
      if (res.code === 200 && res.data) {
        const bankCards = Array.isArray(res.data) ? res.data : [];
        this.setData({
          bankCards: bankCards
        });
      } else {
        wx.showToast({
          title: res.msg || '获取银行卡列表失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('获取银行卡列表失败:', error);
      wx.showToast({
        title: error.message || '获取银行卡列表失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  goBack() {
    wx.navigateBack();
  },

  addBankCard() {
    wx.navigateTo({
      url: '/pages/add-bank-card/add-bank-card'
    });
  },

  /**
   * 点击银行卡卡片查看详情
   */
  viewCardDetail(e: any) {
    const cardId = e.currentTarget.dataset.id;
    this.loadCardDetail(cardId);
  },

  /**
   * 加载银行卡详情
   */
  async loadCardDetail(cardId: number | string) {
    this.setData({ 
      loadingDetail: true,
      showDetailModal: true 
    });
    
    try {
      const res = await BankCardAPI.getBankCardDetail(cardId);
      
      if (res.code === 200 && res.data) {
        this.setData({
          cardDetail: res.data
        });
      } else {
        throw new Error(res.msg || '获取银行卡详情失败');
      }
    } catch (error: any) {
      console.error('获取银行卡详情失败:', error);
      wx.showToast({
        title: error.message || '获取详情失败',
        icon: 'none'
      });
      this.setData({
        showDetailModal: false
      });
    } finally {
      this.setData({ loadingDetail: false });
    }
  },

  /**
   * 关闭详情弹窗
   */
  closeDetailModal() {
    this.setData({
      showDetailModal: false,
      cardDetail: null
    });
  },

  editCard(e: any) {
    const cardId = e.currentTarget.dataset.id;
    // 编辑功能暂时不实现，可以跳转到详情页或编辑页
    wx.showToast({
      title: '编辑功能开发中',
      icon: 'none'
    });
  },

  /**
   * 显示银行卡操作选项
   */
  showCardOptions(e: any) {
    const cardId = e.currentTarget.dataset.id;
    const card = this.data.bankCards.find(item => item.cardId === cardId);
    
    if (!card) {
      return;
    }

    const itemList = [];
    // 如果不是默认卡，显示"设为默认"选项
    if (card.isDefault !== 1) {
      itemList.push('设为默认');
    }
    itemList.push('解绑银行卡');

    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        if (itemList[res.tapIndex] === '设为默认') {
          this.setDefaultBankCard(cardId);
        } else if (itemList[res.tapIndex] === '解绑银行卡') {
          this.deleteBankCard(cardId);
        }
      }
    });
  },

  /**
   * 设置默认银行卡
   */
  async setDefaultBankCard(cardId: number | string) {
    wx.showLoading({ title: '设置中...', mask: true });
    
    try {
      const res = await BankCardAPI.setDefaultBankCard(cardId);
      
      if (res.code === 200) {
        wx.showToast({
          title: '设置成功',
          icon: 'success'
        });
        // 刷新列表
        this.loadBankCardList();
      } else {
        throw new Error(res.msg || '设置失败');
      }
    } catch (error: any) {
      console.error('设置默认银行卡失败:', error);
      wx.showToast({
        title: error.message || '设置失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 阻止事件冒泡（用于编辑和更多按钮）
   */
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  /**
   * 删除银行卡
   */
  deleteBankCard(cardId: number | string) {
    wx.showModal({
      title: '解绑银行卡',
      content: '确定要解绑该银行卡吗？解绑后无法使用该卡进行收款。',
      confirmText: '确定解绑',
      cancelText: '取消',
      success: async (modalRes) => {
        if (modalRes.confirm) {
          wx.showLoading({ title: '解绑中...', mask: true });
          
          try {
            const res = await BankCardAPI.deleteBankCard(cardId);
            
            if (res.code === 200) {
              wx.showToast({
                title: '解绑成功',
                icon: 'success'
              });
              // 刷新列表
              this.loadBankCardList();
            } else {
              throw new Error(res.msg || '解绑失败');
            }
          } catch (error: any) {
            console.error('解绑银行卡失败:', error);
            wx.showToast({
              title: error.message || '解绑失败',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  }
});
